﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using WCF;

namespace geekmeet
{
    /// <summary>
    /// Handles the searchíng and displays search results
    /// </summary>
    public partial class SearchResult : System.Web.UI.Page
    {
        protected GeekMeetService wcf = new GeekMeetService();
        Guid loggedInUserGUID = (Guid)Membership.GetUser().ProviderUserKey;

        protected void Page_Load(object sender, EventArgs e)
        {
            List<int> selectedInterests = new List<int>();
            List<InterestComposite> allInterests = new List<InterestComposite>();

            //Search based on interest and typed in info
            if (Request.QueryString["action"] == ("normalsearch"))
                {
                    
                    MultiViewSearch.SetActiveView(ViewNormalSearch);
                    string hiddenSelectedInterestsValue = Request.Form["hiddenSelectedInterests"];

                    if (hiddenSelectedInterestsValue != "")
                    {
                        hiddenSelectedInterestsValue = hiddenSelectedInterestsValue.Remove(hiddenSelectedInterestsValue.Length - 1, 1);
                    }
                    string[] interestIDs;
                    interestIDs = hiddenSelectedInterestsValue.Split(',').ToArray();

                    foreach (string interest in interestIDs)
                    {
                        int interestID;

                        // For security, check if provided value is valid interestID
                        if (int.TryParse(interest, out interestID) &&
                            allInterests.Where(x => x.InterestID == interestID) != null)
                        {
                            // If yes, add to array of interests
                            // Array posts start at 0...
                            selectedInterests.Add(interestID);
                        }

                    }

                    ContentPlaceHolder mainContentHolder = (ContentPlaceHolder)Page.PreviousPage.Form.FindControl("MainContent");

                    TextBox firstName = (TextBox)mainContentHolder.FindControl("txtFirstName");
                    TextBox lastName = (TextBox)mainContentHolder.FindControl("txtLastName");
                    TextBox userName = (TextBox)mainContentHolder.FindControl("txtUserName");
                    DropDownList gender = (DropDownList)mainContentHolder.FindControl("ddlGender");

                    ProfileComposite p = new ProfileComposite();
                    p.Username = userName.Text;
                    p.FirstName = firstName.Text;
                    p.LastName = lastName.Text;
                    p.Gender = (gender.SelectedValue != "0" ? gender.SelectedValue : null);

                    List<ProfileComposite> results = wcf.SearchUsers(p, selectedInterests, loggedInUserGUID);
                    if (results.Count == 0)
                    {
                        LblNormalSearch.Text = "Tyvärr matchade ingen profil din sökning. Prova igen med nya kriterier!";
                    }
                    else 
                    {
                        normalSearchRepeater.DataSource = results;
                        normalSearchRepeater.DataBind();
                    }
                }
                if (Request.QueryString["action"] == ("findsoulmate"))
                {
                    
                    findSoulmate();
                }
        }

        /// <summary>
        /// The search that is based on the same logic as the matching on a premium users profile
        /// </summary>
        private void findSoulmate()
        {
            List<ProfileComposite> allUsersExceptMe = wcf.GetAllUsersExceptMe(loggedInUserGUID);
            List<Nerdometric> matches = new List<Nerdometric>();
            
            //Calculate matching between me and each user
            foreach (ProfileComposite p in allUsersExceptMe)
            {
                Nerdometric match = new Nerdometric();
                match = match.calculateLove(loggedInUserGUID, p.UserID);
                matches.Add(match);
            }

            //Order the matches by points, decsending, where there is any points. 
            var items = (from m in matches
                    orderby m.MatchPoints descending
                    where m.MatchPoints > 0
                    select m);

            //If there is any result, take top 5 and display them
            if (items.Count() > 0)
            {
                items.Take(5);
                MultiViewSearch.SetActiveView(ViewSoulmateSearchWithMatches);
                soulmateRepeater.DataSource = items;
                soulmateRepeater.DataBind();
            }
            else
            {
                MultiViewSearch.SetActiveView(ViewSoulmateSearchWithoutMatches);
            }
            
        }
    }
}